package assist.base

import net.lingala.zip4j.ZipFile
import net.lingala.zip4j.model.ZipParameters
import net.lingala.zip4j.model.enums.AesKeyStrength
import net.lingala.zip4j.model.enums.EncryptionMethod
import java.io.File

object ZipUtils {
    // 加密压缩
    fun encryptToZip(sourcePath: String, zipPath: String, password: String) {
        val zipParameters = ZipParameters().apply {
            isEncryptFiles = true
            encryptionMethod = EncryptionMethod.AES
            aesKeyStrength = AesKeyStrength.KEY_STRENGTH_256
        }

        val sourceFile = File(sourcePath)
        ZipFile(zipPath, password.toCharArray()).apply {
            if (sourceFile.isDirectory) {
                addFolder(sourceFile, zipParameters)
            } else {
                addFile(sourceFile, zipParameters)
            }
        }
    }

    // 解压解密
    fun decryptZip(zipPath: String, destPath: String, password: String) {
        val zipFile = ZipFile(zipPath, password.toCharArray())

        if (!zipFile.isValidZipFile) {
            throw RuntimeException("Invalid ZIP file")
        }

        if (zipFile.isEncrypted) {
            zipFile.setPassword(password.toCharArray())
        }

        zipFile.extractAll(destPath)
    }
}